import javax.security.auth.callback.Callback;
import java.util.concurrent.*;

/**
 * Created by codeczx on 2018/3/21.
 */
public class Test {

    private static ExecutorService executor = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {
        try {
            timeRun(new Callable() {
                @Override
                public Integer call()  {
                    try {
                        Thread.sleep(5000);
                        System.out.println("done");
                        return 111;
                    } catch (InterruptedException e) {
                        System.out.println("sleep interrupt");
                        e.printStackTrace();
                    }
                    return 222;
                }
            }, 3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void timeRun(Callable callable, long timeout, TimeUnit unit) throws InterruptedException {
        Future future = executor.submit(callable);
        try {
            System.out.println(future.get(timeout,unit));
        } catch (ExecutionException e) {
//            throw new Throwable(e.getCause());
        } catch (TimeoutException e) {
            System.out.println("catch timeout");
        }finally{
            future.cancel(true);
            System.out.println("cancel");
        }
    }
}
